package com.guojunyu.exp3.demo.service;

import com.guojunyu.exp3.demo.entity.Epidemic;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EpidemicService {
    private static final Logger logger = LoggerFactory.getLogger(EpidemicService.class);

    @Value("${resource-url}")
    private String resourceUrl;

    private List<Epidemic> list = new ArrayList<>();

    /**
     * 从指定的url获取数据
     */
    public void getData() {
        // 组装http，使用RestTemplate模拟请求
        RequestEntity<Void> requestEntity = RequestEntity
                    .get(URI.create(resourceUrl))
                    .header("User-Agent", "Mozilla/5.0 (Macintosh;")
                    .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);

        // 清空旧数据
        list.clear();

        try (Reader reader = new InputStreamReader(exchange.getBody().getInputStream()); CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader())) {
            // 遍历处理每一条csv记录
            for (CSVRecord record : parser) {
                Epidemic item = new Epidemic();
                item.setCountry(record.get("Country/Region"));
                item.setProvince(record.get("Province/State"));
                item.setLatitude(Double.parseDouble(record.get("Lat")));
                item.setLongitude(Double.parseDouble(record.get("Long")));
                item.setTotalAmount(Integer.parseInt(record.get(record.size()-1)));
                // 新增确诊 = 最新一天的确诊人数 - 倒数第二天的确诊人数
                item.setModifyAmount(Integer.parseInt(record.get(record.size()-1))-Integer.parseInt(record.get(record.size()-2)));
                list.add(item);
            }

        } catch (IOException e) {
            // 发生IO异常
            logger.error(e.getMessage());
        }

        logger.info("抓取数据成功");
    }

    /**
     * 其他类通过该方法获取list数据
     * @param country
     * @param province
     */
    public List<Epidemic> getEpidemicList(String country, String province) {
        return list.stream()
            .filter((Epidemic item) -> {
               if (!"".equals(country) && !country.equals(item.getCountry()) ||
                   !"".equals(province) && !province.equals(item.getProvince())) {
                    return false;
               }
               return true;
            })
            .collect(Collectors.toList());
    }
}
